import time
import requests

from tools.mytools import *

__file__ = 'zhihudata.py'
__author__ = 'Jerry Liu'
__date__ = '2016-04-21'

seq = []

class Zhihu:

    def __init__(self):
        self.domain = 'https://www.zhihu.com/'
        self.loginurl = 'http://www.zhihu.com/login/email'
        self.followees = 'https://www.zhihu.com/people/%userid/followees'
        self.username = ''
        self.pwd = ''
        self.captcha = ''
        self.xsrf = ''
        self._session = requests.session()
        self.userid = ''

    def getCaptcha(self):
        """
        获取验证码
        :return:
        """
        # 验证码
        t = str(int(time.time() * 1000))
        captcha_url = 'http://www.zhihu.com/captcha.gif?r'+t+'&type=login'
        captcha = self._session.get(captcha_url, stream=True)
        f = open('d://爬虫/知乎壁验证码/captcha.gif', 'wb')
        for line in captcha.iter_content(10):
            f.write(line)
        f.close()


    def doSignin(self):
        """
        登录
        :return:
        """
        self.getCaptcha()
        self.captcha = input('请输入验证码, ')
        # xsrf
        hbody = getBsByGet(self._session, 'https://www.zhihu.com/#signin')
        self.xsrf = ((hbody.find_all('input', attrs={"name": "_xsrf"}))[0]).get('value')
        # 登录
        data = {'email': self.username, 'password': self.pwd, 'captcha': self.captcha, '_xsrf': self.xsrf}
        r = getJson(self._session, self.loginurl,data)
        if r['r'] == 0:
            print('登录成功')
            self.getSetting()
        else:
            print('登录失败,请重试......', r['msg'])
            self.doSignin()

    def getSetting(self):
        """
        设置
        :return:
        """
        # 查询我的userid
        profileHtml = getBsByGet(self._session, 'https://www.zhihu.com/settings/profile')
        self.userid = profileHtml.find_all('input', attrs={'name': 'url_token'})[0].get('value')

    def getMyFollowees(self, userid):
        """
        我关注的人
        :return:
        """
        followeesUrl = self.followees.replace('%userid', userid)
        followeeshtml = getBsByGet(self._session, followeesUrl)
        followeelist = followeeshtml.find_all('a', attrs={'class':'zg-link'})
        for i in range(len(followeelist)):
            followee = followeelist[i]
            fusername = followee.text
            fuserid = followee.get('data-tip')[4:]
            fdomain = followee.get('href')
            data = [userid, fuserid, fusername,fdomain]
            saveMySql(data)
            print(data)


    def getFollowees(self):

        pass


def main():
    zhihu = Zhihu()
    zhihu.doSignin()
    while True:
        cmd = input('请输入操作代码，1 我的关注人 2 关注我的人：')
        cmd = int(cmd)
        if cmd == 1:
            zhihu.getMyFollowees(zhihu.userid)
        elif cmd == 2:
            pass
        else:
            print('命令错误，请重新输入。')
    else:
        print('退出')

if __name__ == '__main__':
    main()